import Taro from "@tarojs/taro";
import { checkTokenIsValid } from "./api/base-api";
import { baseInformation } from "@/libs/api/mine";
/**
 * 移出头尾空格
 * @name trim
 * @memberof String#
 * @returns {string}
 */
export const trim = function(value) {
  return value.replace(/(^\s*)|(\s*$)/g, "");
};

/**
 * 移出所有空格字符（含中文空白字符）
 * @name trimAll
 * @memberof String#
 * @returns {string}
 */
export const trimAll = function(value) {
  return value.replace(/ |　/g, "");
};

/**
 * 消抖执行方法
 * @param {Function} fn 待执行方法
 * @param {Number} delay 消抖延时执行时间。默认180
 */
export const debounce = (fn, delay = 180) => {
  let timer = null;

  return function() {
    let args = arguments;
    let context = this;
    if (timer) {
      clearTimeout(timer);
      timer = setTimeout(function() {
        fn.apply(context, args);
        timer = null;
      }, delay);
    } else {
      timer = setTimeout(function() {
        fn.apply(context, args);
      }, delay);
    }
  };
};

/**
 * 节流执行方法
 * @param {Function} fn 待执行方法
 * @param {Number} delay 节流延时执行时间。默认180
 */
export const throttle = (fn, delay = 180) => {
  let timer = null,
    previous = new Date();

  return function() {
    let now = new Date(),
      remaining = now - previous,
      args = arguments,
      context = this;

    if (remaining >= delay) {
      if (timer) {
        clearTimeout(timer);
      }

      fn.apply(context, args);
      previous = now;
    } else {
      if (!timer) {
        timer = setTimeout(function() {
          fn.apply(context, args);
          previous = new Date();
        }, delay - remaining);
      }
    }
  };
};

/**数字格式化 */
export function formatNumber(number, boundary = 10000) {
  if (number >= boundary) {
    return `${(number / boundary).toFixed(1)}w`;
  }
  return number > 0 ? number : 0;
}

/* 获取页面参数 */
export function getParams() {
  console.log('getParams', Taro.getCurrentInstance().router)
  return Taro.getCurrentInstance().router.params;
}
/**防止暴力点击 */
export function preventForceClick(func) {
  let loading = false;
  return (function(...args) {
    if (loading) return;
    loading = true;
    const passCheck = () => {
      loading = false;
    };
    /**让外部也可以手动取消loading */
    const promise = func.call(this, ...args, passCheck);
    Promise.resolve(promise).finally(() => {
      loading = false;
    });
    return promise;
  })();
}

/**气囊按钮距离顶部的距离 */
export const gasbagHeightMarTop = () => {
  const { height, top } = Taro.getMenuButtonBoundingClientRect();
  return height + top;
};

/**带背景图标题样式 不同机型的信号栏高度不一样 所以不能写死顶部区域的高度
 * @param {number} toGasbagBottom 顶部气囊按钮与盒子第一个元素的的高度
 * @param {number} gasbagToHeight 顶部气囊按钮与盒子最底部的距离
 */
export function hasBackgroundBgTitleStyle(url, toGasbagBottom, gasbagToHeight) {
  const gasbagHeightMarTopDis = gasbagHeightMarTop();
  return {
    "background-image": `url(${url})`,
    "background-size": "100% 100%",
    "padding-top": `calc(${gasbagHeightMarTopDis}px + ${toGasbagBottom}rpx)`,
    height: `calc(${gasbagHeightMarTopDis}px + ${gasbagToHeight}rpx)`
  };
}

/**检验用户是否已获取用户权限 */
// scope.address: true
// scope.invoice: true
// scope.invoiceTitle: true
// scope.userInfo: false
// scope.writePhotosAlbum: true
export function checkIsGetAuth(authType = "userInfo") {
  return new Promise((resolve, reject) => {
    Taro.getSetting({
      success: function(res) {
        const { authSetting } = res;
        authSetting[`scope.${authType}`] ? resolve() : reject(res);
      },
      fail: function(error) {
        reject(error);
      }
    });
  });
}

export const clearToken = () => {
  const oldToken = Taro.getStorageSync("token");
  oldToken && Taro.removeStorageSync("token");
};

/**检验用户是否登录 */
export const checkTokenAuth = () => {
  const token = Taro.getStorageSync("token");
  return !!token;
};

export const toLoginPage = () => {
  Taro.navigateTo({
    url: "/pages/not-login/index"
  });
};

/**按钮前置事件 需要判断是否登录 */
export const handleJudgeIsLogin = () => {
  const hasAuth = checkTokenAuth();
  if (hasAuth) return true;
  toLoginPage();
};

/**处理富文本图片样式 */
export const handleRichTextStyle = text => {
  const replaceImgString =
    '<img style="max-width: 100%;height: auto;margin: 12px 0;"';
  return `<div style="word-break: break-all;">${text.replace(
    /\<img/gi,
    replaceImgString
  )}</div>`;
};

/**获取邀请人id */
export const getInviteId = () => {
  const inviteId = Taro.getStorageSync("invite_id");
  if (inviteId) return inviteId;
};

/**捕获异常错误 */
export const captureCatch = promise => {
  return promise
    .then(res => [null, res])
    .catch(error => (error ? [error, {}] : [{ message: null }, {}]));
};

/**解析二维码参数 */
export const decodeQrcodeScene = (scene = "") => {
  if (!scene) return {};
  let sceneQuery = decodeURIComponent(scene);
  const arrParms = sceneQuery.split("&");
  const query = {};
  // table=1&storeId=1
  for (let i in arrParms) {
    let queryKeys = arrParms[i].split("=");
    query[queryKeys[0]] = queryKeys[1];
  }
  return query;
};

/**活动id
 * 消息通知会通知到用户参与了某个活动
 * 完善信息接口会传入活动id，并在成功时清除掉此id
 */
export const handleSetStorageActivityId = id => {
  id && Taro.setStorageSync("activity_id", id);
};
